package com.yj.timecapsule.interceptor;
import com.yj.timecapsule.common.constant.JwtKey;
import com.yj.timecapsule.common.context.LoginUserContext;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import com.yj.timecapsule.common.utils.JwtUtil;
import com.yj.timecapsule.common.utils.RedisUtil;
import com.yj.timecapsule.entity.user.Users;
import com.yj.timecapsule.entity.user.vo.UserLoginVo;
import com.yj.timecapsule.mapper.UsersMapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Sean
 */
@Component
@Slf4j
public class WebLoginInterceptor implements HandlerInterceptor {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // OPTIONS请求不做校验,
        // 前后端分离的架构, 前端会发一个OPTIONS请求先做预检, 对预检请求不做校验
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        String path = request.getRequestURL().toString();
        log.info("接口登录拦截，path：{}", path);

        //获取header的token参数
        String token = request.getHeader("token");
        log.info("网站登录验证开始，token：{}", token);
        if (token == null || token.isEmpty()) {
            log.info("token为空，请求被拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try {
            String tokenForRedis = redisUtil.get(token).toString();
            log.info("从redis中获取到token : {}",tokenForRedis);
            if (tokenForRedis == null){
                log.info("redis中token为空,用户未登录");
                throw new BusinessException(ErrorCode.USER_NOT_LOGIN);
            }
        }catch (Exception e){

            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            Claims claims = JwtUtil.parse(JwtKey.SECRET_KEY, token);
            log.info("获取会员登录token：{}", token);

            Long userId = Long.valueOf(claims.get("userId").toString());
            Users users = usersMapper.selectByPrimaryKey(userId);
            UserLoginVo loginVo = new UserLoginVo();
            BeanUtils.copyProperties(users, loginVo);
            loginVo.setToken(token);
            LoginUserContext.setUser(loginVo);

            log.info("当前登录会员：{}", loginVo);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LoginUserContext.removeUser();
    }
}
